package cn.xzzz2020.XJynWeb.mvc;

import cn.xzzz2020.XJynWeb.aop.AspectWeaver;
import cn.xzzz2020.XJynWeb.ioc.core.BeanContainer;
import cn.xzzz2020.XJynWeb.ioc.inject.DependencyInjector;
import cn.xzzz2020.XJynWeb.mvc.processor.RequestProcessor;
import cn.xzzz2020.XJynWeb.mvc.processor.impl.ControllerRequestProcessor;
import cn.xzzz2020.XJynWeb.mvc.processor.impl.JspRequestProcessor;
import cn.xzzz2020.XJynWeb.mvc.processor.impl.PreRequestProcessor;
import cn.xzzz2020.XJynWeb.mvc.processor.impl.StaticResourceRequestProcessor;
import cn.xzzz2020.XJynWeb.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


/**
 * 1.完成框架的初始化
 * 2.对请求进行分发
 * 3.对结果进行渲染
 * @author xzzz2020
 * @version 1.0
 * @date 2020/9/4 16:05
 */
@Slf4j
@WebServlet("/*")
public class DispatcherServlet extends HttpServlet {
    //处理器列表
    private List<RequestProcessor> Processor = new ArrayList<>();


    @Override
    public void init(){
        String base_package = this.getInitParameter("base-package");
        BeanContainer beanContainer = BeanContainer.getInstance();
        if (!beanContainer.isLoaded() && ValidationUtil.isEmpty(base_package)){
            throw new RuntimeException("please set base-package in web.xml!!");
        }
        //1.初始化容器
        beanContainer.loadBeans(base_package);
        new AspectWeaver().doAop();
        new DependencyInjector().doIoc();
        //2.初始化请求处理器责任链
        Processor.add(new PreRequestProcessor());
        Processor.add(new StaticResourceRequestProcessor(getServletContext()));
        Processor.add(new JspRequestProcessor(getServletContext()));
        Processor.add(new ControllerRequestProcessor());
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {
        //1.创建责任链对象实例
        RequestProcessorChain requestProcessorChain = new RequestProcessorChain(Processor.iterator(), req, resp);
        //2.通过责任链模式来依次调用请求处理器对请求进行处理
        requestProcessorChain.doRequestProcessorChain();
        //3.对处理结果进行渲染
        requestProcessorChain.doRender();
    }
}
